// CSS解析器相关功能实现

use super::app::FeatureTester;
use eframe::egui;

impl FeatureTester {
    // CSS解析标签页
    pub fn render_css_parser_tab(&mut self, ui: &mut egui::Ui) {
        ui.heading("CSS解析器");

        ui.add_space(10.0);
        ui.label("输入CSS代码:");
        ui.text_edit_multiline(&mut self.css_input);

        ui.add_space(10.0);
        if ui.button("解析CSS").clicked() {
            // 模拟CSS解析过程
            self.css_parse_result =
                format!(
                "CSS解析结果:\n\n规则集数量: {}\n选择器数量: {}\n属性声明数量: {}\n\n解析树:\n{}",
                3, 5, 15,
                self.generate_css_parse_tree(&self.css_input)
            );
        }

        ui.add_space(10.0);
        ui.label("解析结果:");
        ui.add(
            egui::TextEdit::multiline(&mut self.css_parse_result)
                .desired_width(f32::INFINITY)
                .desired_rows(10)
                .frame(true)
                .interactive(false),
        ); // 替换 read_only(true)
    }

    // 选择器解析标签页
    pub fn render_selector_parser_tab(&mut self, ui: &mut egui::Ui) {
        ui.heading("选择器解析器");

        ui.add_space(10.0);
        ui.label("输入CSS选择器:");
        ui.text_edit_singleline(&mut self.css_selector);

        ui.add_space(5.0);
        ui.label("HTML内容:");
        ui.text_edit_multiline(&mut self.html_input);

        ui.add_space(10.0);
        if ui.button("解析选择器").clicked() {
            // 模拟选择器解析过程
            // 解析选择器并应用到HTML上
            let selector = &self.css_selector;
            let html = &self.html_input;

            self.selector_results = format!(
                "选择器 '{}' 解析结果:\n\n选择器类型: {}\n特异性: {}\n\n匹配元素数量: {}\n匹配的第一个元素: {}",
                selector,
                self.determine_selector_type(selector),
                self.calculate_selector_specificity(selector),
                3,
                self.get_first_matched_element(selector, html)
            );
        }

        ui.add_space(10.0);
        ui.label("选择器解析结果:");
        ui.add(
            egui::TextEdit::multiline(&mut self.selector_results)
                .desired_width(f32::INFINITY)
                .desired_rows(8)
                .frame(true)
                .interactive(false),
        ); // 替换 read_only(true)
    }

    // 样式计算标签页
    pub fn render_style_computation_tab(&mut self, ui: &mut egui::Ui) {
        ui.heading("样式计算");

        ui.add_space(10.0);
        ui.horizontal(|ui| {
            ui.vertical(|ui| {
                ui.label("HTML内容:");
                ui.add(
                    egui::TextEdit::multiline(&mut self.html_input)
                        .desired_width(ui.available_width() * 0.48)
                        .desired_rows(10),
                );
            });

            ui.vertical(|ui| {
                ui.label("CSS样式:");
                ui.add(
                    egui::TextEdit::multiline(&mut self.css_input)
                        .desired_width(ui.available_width())
                        .desired_rows(10),
                );
            });
        });

        ui.add_space(10.0);
        ui.label("元素选择器 (用于计算样式):");
        ui.text_edit_singleline(&mut self.css_selector);

        ui.add_space(5.0);
        if ui.button("计算样式").clicked() {
            // 模拟样式计算过程
            self.css_computed_styles =
                self.compute_element_styles(&self.html_input, &self.css_input, &self.css_selector);
        }

        ui.add_space(10.0);
        ui.label("计算后的样式:");
        ui.add(
            egui::TextEdit::multiline(&mut self.css_computed_styles)
                .desired_width(f32::INFINITY)
                .desired_rows(10)
                .frame(true)
                .interactive(false),
        ); // 替换 read_only(true)
    }

    // 媒体查询标签页
    pub fn render_media_query_tab(&mut self, ui: &mut egui::Ui) {
        ui.heading("媒体查询");

        ui.add_space(10.0);
        ui.label("输入包含媒体查询的CSS:");
        ui.text_edit_multiline(&mut self.css_input);

        ui.add_space(10.0);
        ui.collapsing("模拟设备条件", |ui| {
            ui.horizontal(|ui| {
                ui.label("屏幕宽度:");
                ui.add(egui::Slider::new(&mut self.viewport_width, 320.0..=1920.0).text("px"));
            });

            ui.horizontal(|ui| {
                ui.label("屏幕高度:");
                ui.add(egui::Slider::new(&mut self.viewport_height, 240.0..=1080.0).text("px"));
            });

            ui.horizontal(|ui| {
                ui.label("像素比率:");
                ui.add(egui::Slider::new(&mut self.pixel_ratio, 1.0..=3.0).step_by(0.1));
            });

            ui.horizontal(|ui| {
                ui.label("颜色方案:");
                egui::ComboBox::from_id_source("color_scheme")
                    .selected_text(self.color_scheme.clone())
                    .show_ui(ui, |ui| {
                        ui.selectable_value(&mut self.color_scheme, "light".to_string(), "Light");
                        ui.selectable_value(&mut self.color_scheme, "dark".to_string(), "Dark");
                    });
            });

            ui.horizontal(|ui| {
                ui.checkbox(&mut self.is_print_mode, "打印模式");
                ui.checkbox(&mut self.prefers_reduced_motion, "减弱动画");
            });
        });

        ui.add_space(10.0);
        if ui.button("评估媒体查询").clicked() {
            // 模拟媒体查询评估过程
            self.media_query_result = self.evaluate_media_queries(&self.css_input);
        }

        ui.add_space(10.0);
        ui.label("媒体查询评估结果:");
        ui.add(
            egui::TextEdit::multiline(&mut self.media_query_result)
                .desired_width(f32::INFINITY)
                .desired_rows(10)
                .frame(true)
                .interactive(false),
        ); // 替换 read_only(true)
    }

    // CSS动画标签页
    pub fn render_css_animation_tab(&mut self, ui: &mut egui::Ui) {
        ui.heading("CSS动画");

        ui.add_space(10.0);
        ui.label("输入包含动画的CSS:");
        ui.text_edit_multiline(&mut self.css_input);

        ui.add_space(5.0);
        ui.label("HTML内容:");
        ui.text_edit_multiline(&mut self.html_input);

        ui.add_space(10.0);
        ui.horizontal(|ui| {
            if ui.button("解析动画").clicked() {
                // 模拟CSS动画解析过程
                self.animation_info = self.parse_css_animations(&self.css_input);
            }

            if ui.button("播放动画预览").clicked() {
                self.is_animation_playing = !self.is_animation_playing;
            }

            if ui.button("重置动画").clicked() {
                self.animation_progress = 0.0;
                self.is_animation_playing = false;
            }
        });

        // 动画进度滑块
        ui.horizontal(|ui| {
            ui.label("动画进度:");
            ui.add(egui::Slider::new(&mut self.animation_progress, 0.0..=1.0).text("%"));
        });

        ui.add_space(10.0);
        ui.label("动画解析结果:");
        ui.add(
            egui::TextEdit::multiline(&mut self.animation_info)
                .desired_width(f32::INFINITY)
                .desired_rows(8)
                .frame(true)
                .interactive(false),
        ); // 替换 read_only(true));

        ui.add_space(10.0);
        ui.label("动画预览:");
        let (rect, _) = ui.allocate_exact_size(
            egui::vec2(ui.available_width(), 200.0),
            egui::Sense::hover(),
        );

        // 在这里绘制动画预览
        if self.is_animation_playing || self.animation_progress > 0.0 {
            ui.painter()
                .rect_filled(rect, 4.0, egui::Color32::from_rgb(240, 240, 240));

            // 绘制一个简单的示例动画（一个移动和变色的方块）
            let progress = if self.is_animation_playing {
                // 如果在播放中，使用ctx.animate_value更新进度
                ui.ctx().animate_value_with_time(
                    ui.id().with("anim_progress"),
                    if self.animation_progress >= 1.0 {
                        0.0
                    } else {
                        1.0
                    },
                    2.0,
                ) // 2秒一个循环
            } else {
                self.animation_progress
            };

            let size = 50.0;
            let x_pos = rect.min.x + progress * (rect.width() - size);
            let y_pos = rect.min.y + (rect.height() - size) / 2.0;

            // 颜色动画
            let r = (255.0 * progress) as u8;
            // 修复类型转换问题
            let g = (100.0 + (155.0 * (1.0 - progress))) as u8;
            let b = (200.0 + (55.0 * progress.sin())) as u8;

            ui.painter().rect_filled(
                egui::Rect::from_min_size(egui::pos2(x_pos, y_pos), egui::vec2(size, size)),
                8.0 + 8.0 * progress.sin() as f32, // 圆角动画
                egui::Color32::from_rgb(r, g, b),
            );
        } else {
            ui.painter().text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                "点击",
                egui::FontId::default(),
                egui::Color32::GRAY,
            );
        }
    }

    // CSS解析器辅助方法
    fn generate_css_parse_tree(&self, css: &str) -> String {
        let mut result = String::new();

        // 简单模拟CSS解析树
        result.push_str("StyleSheet\n");

        let mut indent = 2;
        let indentation = " ".repeat(indent);

        for line in css.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            if line.contains("{") {
                // 选择器开始
                result.push_str(&format!("{}┣━ RuleSet\n", indentation));
                indent += 2;
                let indentation = " ".repeat(indent);
                result.push_str(&format!(
                    "{}┣━ Selector: \"{}\"\n",
                    indentation,
                    line.trim_end_matches('{')
                ));
                result.push_str(&format!("{}┗━ Declaration Block\n", indentation));
                indent += 2;
            } else if line.contains("}") {
                // 规则结束
                indent -= 4;
            } else if line.contains(":") {
                // 属性声明
                let parts: Vec<&str> = line.split(':').collect();
                if parts.len() >= 2 {
                    let prop = parts[0].trim();
                    let value = parts[1].trim().trim_end_matches(';');
                    let indentation = " ".repeat(indent);
                    result.push_str(&format!(
                        "{}┣━ Declaration: {} = {}\n",
                        indentation, prop, value
                    ));
                }
            }
        }

        result
    }

    fn determine_selector_type(&self, selector: &str) -> String {
        if selector.contains("#") {
            return "ID选择器".to_string();
        } else if selector.contains(".") {
            return "类选择器".to_string();
        } else if selector.contains("[") {
            return "属性选择器".to_string();
        } else if selector.contains(":") {
            return "伪类/伪元素选择器".to_string();
        } else if selector.contains(">") {
            return "子元素选择器".to_string();
        } else if selector.contains("+") {
            return "相邻兄弟选择器".to_string();
        } else if selector.contains("~") {
            return "通用兄弟选择器".to_string();
        } else if selector.contains(" ") {
            return "后代选择器".to_string();
        } else {
            return "元素选择器".to_string();
        }
    }

    fn calculate_selector_specificity(&self, selector: &str) -> String {
        // 简化的特异性计算
        let id_count = selector.matches('#').count();
        let class_count = selector.matches('.').count()
            + selector.matches('[').count()
            + selector.matches(':').count();
        let element_count = selector
            .split(|c: char| !c.is_alphabetic())
            .filter(|s| !s.is_empty())
            .count()
            - (id_count + class_count); // 调整元素计数

        format!("({}, {}, {})", id_count, class_count, element_count)
    }

    fn get_first_matched_element(&self, _selector: &str, _html: &str) -> String {
        // 这里应该通过解析HTML和应用选择器来找到第一个匹配元素
        // 简化版本，返回模拟的结果
        "<div class=\"container\">...</div>".to_string()
    }

    fn compute_element_styles(&self, _html: &str, css: &str, selector: &str) -> String {
        let mut result = String::new();

        result.push_str(&format!("选择器 \"{}\" 的计算样式:\n\n", selector));
        result.push_str("┌──────────────────────────────────────────────\n");

        // 模拟样式计算过程
        let mut computed_props: Vec<(String, String)> = Vec::new();

        // 添加一些默认样式（浏览器默认）
        computed_props.push(("display".to_string(), "block".to_string()));
        computed_props.push(("margin".to_string(), "0".to_string()));
        computed_props.push(("padding".to_string(), "0".to_string()));
        computed_props.push(("color".to_string(), "#000000".to_string()));
        computed_props.push(("font-size".to_string(), "16px".to_string()));

        // 从CSS中提取匹配的样式
        let in_matching_rule = false;
        for line in css.lines() {
            let line = line.trim();

            if line.is_empty() {
                continue;
            }

            if line.contains("{") {
                // 假设这是一个匹配的规则
                if line.contains(selector.split(' ').next().unwrap_or("")) {
                    let in_matching_rule = true;
                }
            } else if line.contains("}") {
                let in_matching_rule = false;
            } else if let in_matching_rule = true {
                if line.contains(":") {
                    let parts: Vec<&str> = line.split(':').collect();
                    if parts.len() >= 2 {
                        let prop = parts[0].trim().to_string();
                        let value = parts[1].trim().trim_end_matches(';').to_string();

                        // 更新或添加属性
                        if let Some(pos) = computed_props.iter().position(|(p, _)| p == &prop) {
                            computed_props[pos] = (prop, value);
                        } else {
                            computed_props.push((prop, value));
                        }
                    }
                }
            }
        }

        // 添加继承的属性
        computed_props.push(("font-family".to_string(), "inherit".to_string()));

        // 排序并显示最终计算出的属性
        computed_props.sort_by(|(a, _), (b, _)| a.cmp(b));

        for (prop, value) in computed_props {
            result.push_str(&format!("│ {}: {}\n", prop, value));
        }

        result.push_str("└──────────────────────────────────────────────\n\n");
        result.push_str("层叠顺序:\n");
        result.push_str("1. 用户代理样式表（浏览器默认）\n");
        result.push_str("2. 用户样式表\n");
        result.push_str("3. 作者样式表（页面CSS）\n");
        result.push_str("4. !important 声明\n");

        result
    }

    fn evaluate_media_queries(&self, css: &str) -> String {
        let mut result = String::new();

        result.push_str("媒体查询评估结果:\n\n");

        // 提取并评估媒体查询
        let mut media_queries = Vec::new();
        let mut current_query = String::new();
        let mut in_media_block = false;

        for line in css.lines() {
            let line = line.trim();

            if line.starts_with("@media") {
                in_media_block = true;
                current_query = line.to_string();
            } else if in_media_block && line.contains("}") {
                in_media_block = false;
                media_queries.push(current_query.clone());
                current_query.clear();
            }
        }

        if media_queries.is_empty() {
            result.push_str("未检测到媒体查询。\n");
        } else {
            result.push_str(&format!("检测到 {} 个媒体查询:\n\n", media_queries.len()));

            for (i, query) in media_queries.iter().enumerate() {
                result.push_str(&format!("{}. {}\n", i + 1, query));

                // 评估媒体查询是否匹配
                let matches = if query.contains("min-width") {
                    let min_width = 768.0; // 假设从查询中提取的值
                    self.viewport_width >= min_width
                } else if query.contains("max-width") {
                    let max_width = 1024.0; // 假设从查询中提取的值
                    self.viewport_width <= max_width
                } else if query.contains("print") {
                    self.is_print_mode
                } else if query.contains("prefers-color-scheme") {
                    query.contains(&self.color_scheme)
                } else if query.contains("prefers-reduced-motion") {
                    self.prefers_reduced_motion
                } else {
                    // 默认不匹配
                    false
                };

                result.push_str(&format!(
                    "   匹配当前条件: {}\n",
                    if matches { "是" } else { "否" }
                ));
                result.push_str("\n");
            }
        }

        // 添加当前媒体环境
        result.push_str("当前媒体环境:\n");
        result.push_str(&format!(
            "- 视口尺寸: {}x{} px\n",
            self.viewport_width, self.viewport_height
        ));
        result.push_str(&format!("- 像素比率: {}\n", self.pixel_ratio));
        result.push_str(&format!("- 颜色方案: {}\n", self.color_scheme));
        result.push_str(&format!(
            "- 打印模式: {}\n",
            if self.is_print_mode {
                "开启"
            } else {
                "关闭"
            }
        ));
        result.push_str(&format!(
            "- 减弱动画: {}\n",
            if self.prefers_reduced_motion {
                "开启"
            } else {
                "关闭"
            }
        ));

        result
    }

    fn parse_css_animations(&self, css: &str) -> String {
        let mut result = String::new();

        result.push_str("CSS动画解析结果:\n\n");

        // 检测@keyframes规则
        let mut keyframes = Vec::new();
        let mut current_keyframe = String::new();
        let mut in_keyframes = false;
        let mut keyframe_name = String::new();

        for line in css.lines() {
            let line = line.trim();

            if line.starts_with("@keyframes") {
                in_keyframes = true;
                keyframe_name = line.replace("@keyframes", "").trim().to_string();
                current_keyframe = format!("@keyframes {}", keyframe_name);
            } else if in_keyframes && line.contains("}") && !line.contains("{") {
                in_keyframes = false;
                keyframes.push((keyframe_name.clone(), current_keyframe.clone()));
                current_keyframe.clear();
                keyframe_name.clear();
            } else if in_keyframes {
                current_keyframe.push_str("\n");
                current_keyframe.push_str(line);
            }
        }

        // 检测动画属性
        let mut animations = Vec::new();

        for line in css.lines() {
            let line = line.trim();

            if line.contains("animation") || line.contains("animation-") {
                animations.push(line.to_string());
            }
        }

        // 显示解析结果
        if keyframes.is_empty() {
            result.push_str("未检测到@keyframes规则。\n");
        } else {
            result.push_str(&format!("检测到 {} 个@keyframes规则:\n\n", keyframes.len()));

            for (name, _) in &keyframes {
                result.push_str(&format!("- {}\n", name));
            }

            result.push_str("\n");
        }

        if animations.is_empty() {
            result.push_str("未检测到动画属性。\n");
        } else {
            result.push_str(&format!("检测到 {} 个动画属性:\n\n", animations.len()));

            for anim in &animations {
                result.push_str(&format!("- {}\n", anim));
            }

            result.push_str("\n");
        }

        // 添加动画分析
        if !keyframes.is_empty() && !animations.is_empty() {
            result.push_str("动画分析:\n");
            result.push_str("- 动画持续时间: 1s\n");
            result.push_str("- 动画时间函数: ease\n");
            result.push_str("- 动画延迟: 0s\n");
            result.push_str("- 动画迭代次数: infinite\n");
            result.push_str("- 动画方向: normal\n");
            result.push_str("- 动画填充模式: none\n");
        }

        result
    }
}

// 添加CSS解析器模块需要的额外字段
impl FeatureTester {
    // 初始化CSS解析相关的字段
    pub fn init_css_parser_fields(&mut self) {
        self.viewport_width = 1024.0;
        self.viewport_height = 768.0;
        self.pixel_ratio = 1.0;
        self.color_scheme = "light".to_string();
        self.is_print_mode = false;
        self.prefers_reduced_motion = false;
        self.animation_progress = 0.0;
        self.is_animation_playing = false;
        self.animation_info = String::new();
    }
}
